//
//  MCHomePageViewController.m
//  ERP
//
//  Created by goldeney on 15/1/15.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MCHomePageViewController.h"
//#import "ReportFormsViewController.h"
#import "MCWarehouseViewController.h"
//#import "WebReportFormsViewController.h"

#import "MCChargeInViewController.h"
#import "MCConsumeViewController.h"

#import "TableOneButtonViewCell.h"
#import "TTScrollSlidingPagesController.h"
#import "TTSlidingPage.h"
#import "TTSlidingPageTitle.h"
#import "GEDateFromatter.h"

#import "GEObjectValueTableViewCell.h"
#import "GEProgressBarTableViewCell.h"

#import "PNChart.h"
#import "Charts-Swift.h"
#import "KLCPopup.h"
#import "KWFormViewQuickBuilder.h"
#import "GEObjectButton.h"
#import "GEShowMutliPopupReportView.h"
#import "DateTimeFormat.h"
#import "StringAxisValueFormatter.h"

#import "JXBarChartView.h"
#import "GEWeekTimeFromatter.h"
#import "NSDictionary+DataFormat.h"
#import "UIView+AssistView.h"

@interface MCHomePageViewController ()<TTSlidingPagesDataSource, TTSliddingPageDelegate,ChartViewDelegate>

@property (nonatomic,strong) TTScrollSlidingPagesController *slider;
@property (nonatomic, strong) NSMutableArray *sectionInfoArray;

@end

@implementation MCHomePageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"原材管理"];
        [self addStationToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    [self getModelAuthority];//菜单权限设置
}

- (void)dealloc
{
    [self.tableView removeAllSaveCell];
    [self.tableView removeFromSuperview];
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    self.tableView = nil;
}

#pragma make - Station Notification

-(void)updateStationNotification:(ModuleAuthorityEntity*)model
{
    [self.tableView removeAllSaveCell];
    [self.tableView reloadData];
}

#pragma make
#pragma make - 菜单权限设置

- (void)getModelAuthority
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"codeType = 0 and (permissionsMark = 'PM_YCGL_YCJL' or permissionsMark = 'PM_YCGL_YCXH')"];
    NSArray *mainMenuArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:predicate];
    
    //页面数据配置
    self.sectionInfoArray = [NSMutableArray array];
    for (ModuleAuthorityEntity *model in mainMenuArray) {
        if([model.permissionsMark isEqualToString:@"PM_YCGL_SSKC"])
            [self.sectionInfoArray addObject:@"YCSSKC"];//原材实时库存
        else if([model.permissionsMark isEqualToString:@"PM_YCGL_YCJL"])
            [self.sectionInfoArray addObject:@"YCJLTJ"];//原材进料统计
        else if([model.permissionsMark isEqualToString:@"PM_YCGL_YCXH"])
            [self.sectionInfoArray addObject:@"YCJXCTJ"];//原材消耗统计
    }
    [self.tableView reloadData];
    
    //未找到模块，显示提示页面
    if(self.sectionInfoArray.count <= 0){
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.tableView showPromptViewText:@"暂无模块" rect:CGRectMake(0, 0, SuperWidth, SuperHeight - 128) blcok:nil];
    }
}

#pragma mark - 原材实时库存

- (void)materialRealTimeInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"当前原材实时库存容量（吨）";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    GEObjectButton *subLable = [[GEObjectButton alloc] initWithFrame:CGRectMake(20, 28, SuperWidth - 40, 32)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:subLable];
    subLable.userInteractionEnabled = YES;
    subLable.object = cell.objectValue;
    [subLable addTarget:self action:@selector(realTimeSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *nowTime = [DateTimeFormat getNowDateFormatter:@"yyyy-MM-dd HH:mm:ss"];
    NSString *showString = [NSString stringWithFormat:@"以下为%@数据  明细",nowTime];
    NSMutableAttributedString *lableText = [[NSMutableAttributedString alloc] initWithString:showString];
    [lableText addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle],
                               NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f] } range:NSMakeRange(lableText.length - 2, 2)];
    [subLable setAttributedTitle:lableText forState:UIControlStateNormal];
    
    //无数据绘制提示
    if (cell.objectValue.count <= 0) {
        [cell drawNotDataViewTableView:self.tableView rect:CGRectMake(0, 60, SuperWidth, 180)];
        return;
    }
    
    self.slider = [[TTScrollSlidingPagesController alloc] initWithRect:CGRectMake(0, 50.0, SCREEN_WIDTH, 250.0)];
    self.slider.titleScrollerInActiveTextColour = [UIColor colorWithWhite:0.92 alpha:1];
    self.slider.titleScrollerBottomEdgeColour = [UIColor colorWithWhite:0.92 alpha:1];
    self.slider.titleScrollerBottomEdgeHeight = 2;
    self.slider.object = cell.objectValue;
    self.slider.dataSource = self;
    [cell.contentView addSubview:self.slider.view];
}

#pragma mark - 原材进料统计

- (void)materialChargeInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"原材运单量与实际量对比分析(吨)";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    GEObjectButton *subLable = [[GEObjectButton alloc] initWithFrame:CGRectMake(20, 26, SuperWidth - 40, 32)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:subLable];
    subLable.userInteractionEnabled = YES;
    subLable.object = valueArray;
    [subLable addTarget:self action:@selector(changeSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *showString = [NSString stringWithFormat:@"以下为近3天数据  明细"];
    NSMutableAttributedString *lableText = [[NSMutableAttributedString alloc] initWithString:showString];
    [lableText addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle],
                               NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f] } range:NSMakeRange(lableText.length - 2, 2)];
    [subLable setAttributedTitle:lableText forState:UIControlStateNormal];
    
    //无数据绘制提示
    if (valueArray.count <= 0) {
        [cell drawNotDataViewTableView:self.tableView rect:CGRectMake(0, 60, SuperWidth, 180)];
        return;
    }
    
    BarChartView *_chartView = [[BarChartView alloc] initWithFrame:CGRectMake(0, 60, SCREEN_WIDTH, 245.0)];
//    _chartView.descriptionText = @"";
    _chartView.noDataText = @"暂无数据";
    
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawBarShadowEnabled = NO;
    _chartView.drawGridBackgroundEnabled = NO;
    
    ChartLegend *legend = _chartView.legend;
    legend.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    legend.verticalAlignment = ChartLegendVerticalAlignmentTop;
    legend.orientation = ChartLegendOrientationVertical;
    legend.drawInside = YES;
    legend.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:8.f];
    legend.yOffset = 10.0;
    legend.xOffset = 10.0;
    legend.yEntrySpace = 0.0;
    
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    xAxis.labelPosition = XAxisLabelPositionBothSided;
    xAxis.granularity = 1.f;
    xAxis.centerAxisLabelsEnabled = YES;
    
    ChartYAxis *leftAxis = _chartView.leftAxis;
    leftAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    leftAxis.drawGridLinesEnabled = NO;
    leftAxis.spaceTop = 0.35;
    leftAxis.axisMinimum = 0.0; // this replaces startAtZero = YES

    _chartView.rightAxis.enabled = NO;
    
    _chartView.data = [self generateBar:_chartView data:valueArray];
    [cell.contentView addSubview:_chartView];
}

- (BarChartData *)generateBar:(BarChartView*)chartView data:(NSArray*)array
{
    NSInteger groupCount = array.count;
    float groupSpace = 0.1f;
    float barSpace = 0.05f;
    float barWidth = 0.25f;
    // (0.25 + 0.05) * 3 + 0.1 = 1.00 -> interval per "group"
    
    NSMutableArray *xVals = [NSMutableArray array];
    for (int j = 0; j < array.count; j++) {
        NSDictionary *mDictionary = [array objectAtIndex:j];
        NSString *clmc = [mDictionary objectFormatStringForKey:@"材料名称"];
        [xVals addObject:clmc];
    }
    
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    NSMutableArray *yVals2 = [[NSMutableArray alloc] init];
    NSMutableArray *yVals3 = [[NSMutableArray alloc] init];
    for (int i = 0; i < array.count; i++) {
        NSDictionary *mDictionary = [array objectAtIndex:i];
        
        CGFloat weight1 = [mDictionary objectFormatFloatForKey:@"净重" retain:1 except:1];
        [yVals1 addObject:[[BarChartDataEntry alloc] initWithX:i y:weight1]];
        
        CGFloat weight2 = [mDictionary objectFormatFloatForKey:@"供方重量" retain:1 except:1];
        [yVals2 addObject:[[BarChartDataEntry alloc] initWithX:i y:weight2]];
        
        CGFloat weight3 = fabs(weight2 - weight1);
        [yVals3 addObject:[[BarChartDataEntry alloc] initWithX:i y:weight3]];
    }
    //设置底部显示文字
    chartView.xAxis.granularity = 1.0; // only intervals 
    chartView.xAxis.valueFormatter = [[StringAxisValueFormatter alloc] initWithData:xVals];
    
    BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithValues:yVals1 label:@"实际重量"];
    [set1 setColor:ThemeColorGreen];
    BarChartDataSet *set2 = [[BarChartDataSet alloc] initWithValues:yVals2 label:@"运单重量"];
    [set2 setColor:ThemeColorLigthBlue];
    BarChartDataSet *set3 = [[BarChartDataSet alloc] initWithValues:yVals3 label:@"供方偏差"];
    [set3 setColor:ThemeColorOrange];
    
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];
    [dataSets addObject:set2];
    [dataSets addObject:set3];
    
    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    [data setDrawValues:YES];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];
    
    // specify the width each bar should have
    data.barWidth = barWidth;
    
    // restrict the x-axis range
    chartView.xAxis.axisMinimum = 0;
    
    // groupWidthWithGroupSpace(...) is a helper that calculates the width each group needs based on the provided parameters
    chartView.xAxis.axisMaximum = [data groupWidthWithGroupSpace:groupSpace barSpace: barSpace] * groupCount;
    
    [data groupBarsFromX:0 groupSpace:groupSpace barSpace:barSpace];
    
    return data;
}

#pragma mark - 原材消耗统计

- (void)materialConsumeInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"原材当日消耗统计分析(吨)";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    GEObjectButton *subLable = [[GEObjectButton alloc] initWithFrame:CGRectMake(20, 26, SuperWidth - 40, 32)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:subLable];
    subLable.userInteractionEnabled = YES;
    subLable.object = valueArray;
    //[subLable addTarget:self action:@selector(changeXHSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *nowTime = [DateTimeFormat getNowDateFormatter:@"yyyy-MM-dd HH:mm:ss"];
    NSString *showString = [NSString stringWithFormat:@"以下为%@数据",nowTime];
    //NSString *showString = [NSString stringWithFormat:@"以下为%@数据  明细",nowTime];
    NSMutableAttributedString *lableText = [[NSMutableAttributedString alloc] initWithString:showString];
//    [lableText addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle],
//                               NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f] } range:NSMakeRange(lableText.length - 2, 2)];
    [subLable setAttributedTitle:lableText forState:UIControlStateNormal];
    
    //无数据绘制提示
    if (valueArray.count <= 0) {
        [cell drawNotDataViewTableView:self.tableView rect:CGRectMake(0, 60, SuperWidth, 180)];
        return;
    }
    
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, 46, SCREEN_WIDTH, 260.0)];
    _chartView.holeRadiusPercent = 0.38;
    _chartView.transparentCircleRadiusPercent = 0.39;
//    _chartView.descriptionText = @"";
    _chartView.noDataText = @"";
    _chartView.drawCenterTextEnabled = YES;
    [_chartView setExtraOffsetsWithLeft:5.f top:10.f right:5.f bottom:5.f];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    CGFloat numberValue = 0;
    for (int i = 0; i < valueArray.count; i++){
        NSDictionary *mDictionary = [valueArray objectAtIndex:i];
        numberValue += [mDictionary objectFormatFloatForKey:@"消耗量"];
    }
    
    NSString *xhzl = [NSString stringWithFormat:@"%0.2ft",numberValue];
    NSString *text = [NSString stringWithFormat:@"%@\n消耗总量",xhzl];
    NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:text];
    [centerText setAttributes:@{
                                NSFontAttributeName:[UIFont boldSystemFontOfSize:14.0f],
                                NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName:ThemeColorOrange
                                } range:NSMakeRange(0, xhzl.length)];
    [centerText setAttributes:@{
                                NSFontAttributeName:[UIFont boldSystemFontOfSize:13.0f],
                                NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName:[UIColor grayColor]
                                } range:NSMakeRange(text.length - 4, 4)];
    _chartView.centerAttributedText = centerText;
    
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.0;
    _chartView.rotationEnabled = YES;
    _chartView.highlightPerTapEnabled = YES;
    
    _chartView.drawEntryLabelsEnabled = NO;
    _chartView.usePercentValuesEnabled = NO;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentLeft;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.font = [UIFont systemFontOfSize:11];
    
    [self setMaterialConsumeData:_chartView data:valueArray];
    [_chartView animateWithXAxisDuration:1.4 yAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];
    [cell.contentView addSubview:_chartView];
    
}

- (void)setMaterialConsumeData:(PieChartView *)_chartView data:(NSArray*)array
{
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    for (int i = 0; i < array.count; i++){
        NSDictionary *mDictionary = [array objectAtIndex:i];
        CGFloat value = [mDictionary objectFormatFloatForKey:@"消耗量"];
        CGFloat numberValue = [mDictionary objectFormatFloatForKey:@"消耗量" retain:2 except:1];
        NSString *titleValue = [mDictionary objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        NSString *valueNameStr = [NSString stringWithFormat:@"%@  %0.2f吨",titleValue,numberValue];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:value label:valueNameStr]];
    }
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@"原材消耗种类"];
    dataSet.sliceSpace = 2.0;
    dataSet.drawValuesEnabled = NO;
    //dataSet.drawIconsEnabled = NO;
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:ThemeColorGreen];
    [colors addObject:ThemeColorLigthBlue];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    dataSet.colors = colors;
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @"T";
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    _chartView.data = data;
    [_chartView highlightValues:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark TTSlidingPagesDataSource methods
-(NSInteger)numberOfPagesForSlidingPagesViewController:(TTScrollSlidingPagesController *)source
{
    NSArray *valueArray = source.object;
    if (valueArray && valueArray.count > 0) return valueArray.count - 1;
    else return 0;
}

-(TTSlidingPage *)pageForSlidingPagesViewController:(TTScrollSlidingPagesController*)source atIndex:(int)index
{
    NSArray *valueArray = source.object;
    NSArray *value = [valueArray objectAtIndex:index + 1];
    CGFloat MaxStereValue = 0;
    
    //柱状图名称
    NSMutableArray * data01Array = [NSMutableArray array];
    for (int i=0; i<value.count; i++) {
        NSDictionary *mDictionary = [value objectAtIndex:i];
        NSString *Sys_Material_Norms = [mDictionary objectFormatStringForKey:@"仓储位置" defaults:@"-"];
        NSString *valueString = [NSString stringWithFormat:@"%@",Sys_Material_Norms];
        [data01Array addObject:valueString];
    }
    
    //最大值
    NSMutableArray * data02Array = [NSMutableArray array];
    for (int i=0; i<value.count; i++) {
        NSDictionary *mDictionary = [value objectAtIndex:i];
        NSString *MaxStere = [mDictionary objectFormatStringForKey:@"最大数量"];
        CGFloat floatValue = [MaxStere floatValue];
        MaxStereValue = floatValue > MaxStereValue ? floatValue : MaxStereValue;
        [data02Array addObject:[NSNumber numberWithFloat:floatValue]];
    }
    
    //百分百
    NSMutableArray * data03Array = [NSMutableArray array];
    for (int i=0; i<value.count; i++) {
        NSDictionary *mDictionary = [value objectAtIndex:i];
        CGFloat MaxStere = [[mDictionary objectFormatStringForKey:@"最大数量"] floatValue];
        CGFloat Stere = [[mDictionary objectFormatStringForKey:@"剩余数量"] floatValue];
        CGFloat floatValue = Stere/MaxStere*100;
        [data03Array addObject:[NSNumber numberWithFloat:floatValue]];
    }
    
    PNBarChart *barChart = [[PNBarChart alloc] initWithFrame:CGRectMake(5, 0, SCREEN_WIDTH, 220)];
    barChart.backgroundColor = [UIColor clearColor];
    barChart.yLabelFormatter = ^(CGFloat yValue){
        CGFloat yValueParsed = yValue;
        NSString * labelText = [NSString stringWithFormat:@" %1.f%%",yValueParsed];
        return labelText;
    };
    barChart.labelMarginTop = 5.0;
    [barChart setXLabels:data01Array];
//    barChart.rotateForXAxisText = true;
    barChart.showChartBorder = YES;
    barChart.showLabel = YES;
    barChart.yMaxValue = 100;
    [barChart setYTopValues:data02Array];
    [barChart setYValues:data03Array];
//    [barChart setStrokeColors:@[ThemeColorGreen]];
    [barChart setStrokeColor:ThemeColorGreen];
    // Adding gradient
//    barChart.barColorGradientStart = ThemeColorGreen;
    [barChart strokeChart];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 220.0)];
    [view addSubview:barChart];
    return [[TTSlidingPage alloc] initWithContentView:view];
}

-(TTSlidingPageTitle *)titleForSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(int)index
{
    NSArray *valueArray = source.object;
    NSArray *nowArray = [valueArray firstObject];
    NSDictionary *dicValue = [nowArray objectAtIndex:index];
    NSString *ckmc = [dicValue objectFormatStringForKey:@"生产线" defaults:@"未知"];
    
    TTSlidingPageTitle *title = [[TTSlidingPageTitle alloc] initWithHeaderText:ckmc];
    return title;
}

#pragma mark - delegate
-(void)didScrollToViewAtIndex:(NSUInteger)index
{
    NSLog(@"scrolled to view");
}

#pragma mark - ChartViewDelegate

- (void)chartScaled:(ChartViewBase *)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY
{
    
}

#pragma mark
#pragma mark - UITableViewDataSource

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionInfoArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    GEProgressBarTableViewCell *cell = [self.tableView getCellViewInRow:0 inSection:section];
    if (cell && cell.objectValue) return 2;
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        return [self drawChartTableView:tableView cellForRowAtIndexPath:indexPath];
    } else {
        return [self drawModuleButtonTableView:tableView cellForRowAtIndexPath:indexPath];
    }
}

- (UITableViewCell *)drawChartTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //绘制图表数据
    GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
    if (progressBarCell == nil) {
        NSString *identifierBar = [NSString stringWithFormat:@"MCGEProgressBarTableViewCell%ld",indexPath.section];
        progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar];
        progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
    }
    
    //判读有无数据，有数据就加载页面
    if(progressBarCell.objectValue){
        NSString *identifier = [NSString stringWithFormat:@"MCGEObjectValueTableViewCell%ld",(long)indexPath.section];
        //GEObjectValueTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        GEObjectValueTableViewCell *cell = [self.tableView getCellViewKey:identifier];
        if (cell == nil) {
            cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            [self.tableView setCellView:cell key:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.objectValue = progressBarCell.objectValue;
            //添加图表
            NSString *identification = self.sectionInfoArray[indexPath.section];
            if([identification isEqualToString:@"YCSSKC"]){ //原材实时库存
                [self materialRealTimeInCell:cell indexPath:indexPath];
            } else if([identification isEqualToString:@"YCJLTJ"]){ //原材进料统计
                [self materialChargeInCell:cell indexPath:indexPath];
            } else if([identification isEqualToString:@"YCJXCTJ"]){ //原材消耗统计
                [self materialConsumeInCell:cell indexPath:indexPath];
            }
        }
        return cell;
    }
    
    //绘制进度条,并加载数据
    NSString *identification = self.sectionInfoArray[indexPath.section];
    if ([identification isEqualToString:@"YCSSKC"]) { //原材实时库存
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"YCL_SSKC_CHART" parameter:nil index:indexPath.section];
    } else if ([identification isEqualToString:@"YCJLTJ"]) { //原材进料统计
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"YCL_JLTJ_CHART_20160108" parameter:nil index:indexPath.section];
    } else if ([identification isEqualToString:@"YCJXCTJ"]) { //原材消耗统计 “YCL_JXCTJ_CHART”作废
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"YCL_DRXH_CHART" parameter:nil index:indexPath.section];
    }
    return progressBarCell;
}

//绘制功能按钮
- (UITableViewCell *)drawModuleButtonTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifierOne = [NSString stringWithFormat:@"MCTableOneButtonViewCell%ld=%ld",(long)indexPath.section,indexPath.row];
    TableOneButtonViewCell *cellOne = [tableView dequeueReusableCellWithIdentifier:identifierOne];
    if (cellOne == nil) {
        cellOne = [[TableOneButtonViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierOne];
        cellOne.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    
    NSString *identification = self.sectionInfoArray[indexPath.section];
    if([identification isEqualToString:@"YCSSKC"] && indexPath.row == 1){//原材实时库存
        cellOne.titleLable.text = @"原材实时库存报表";
        cellOne.explainLable.text = @"默认当前时间数据";
    } else if([identification isEqualToString:@"YCJLTJ"] && indexPath.row == 1){//原材进料统计
        cellOne.titleLable.text = @"原材进料统计分析";
        cellOne.explainLable.text = @"默认当前月份数据";
    } else if([identification isEqualToString:@"YCJXCTJ"] && indexPath.row == 1){//原材消耗统计
        cellOne.titleLable.text = @"原材消耗统计分析";
        cellOne.explainLable.text = @"默认当前月份数据";
    }
    
    return cellOne;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = ThemeColorBlue;
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    NSString *identification = self.sectionInfoArray[section];
    if ([identification isEqualToString:@"YCSSKC"]) {
        lable.text = @"原材实时库存";
    } else if([identification isEqualToString:@"YCJLTJ"]){
        lable.text = @"原材进料统计";
    } else if([identification isEqualToString:@"YCJXCTJ"]){
        lable.text = @"原材消耗统计";
    }
    [view addSubview:lable];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GEProgressBarTableViewCell *cell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
    if(!(cell && cell.objectValue)) return 240;
    
    NSArray *valueArray = [cell.objectValue firstObject];
    if (valueArray.count <= 0 && indexPath.row == 0) return 240;
    
    NSString *identification = self.sectionInfoArray[indexPath.section];
    if([identification isEqualToString:@"YCSSKC"] && indexPath.row == 0){
        return 295;
    } else if([identification isEqualToString:@"YCJLTJ"] && indexPath.row == 0){
        return 320;
    } else if([identification isEqualToString:@"YCJXCTJ"] && indexPath.row == 0){
        return 300;
    }
    
    return 52;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *identification = self.sectionInfoArray[indexPath.section];
    
    if([identification isEqualToString:@"YCSSKC"] && indexPath.row == 1){
        GEProgressBarTableViewCell *cell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        //NSArray *value = [cell.objectValue objectAtIndex:0];
        MCWarehouseViewController *viewController = [[MCWarehouseViewController alloc] initWithValue:cell.objectValue];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if([identification isEqualToString:@"YCJLTJ"] && indexPath.row == 1){
        //原材进料类统计报表
        MCChargeInViewController *viewController = [[MCChargeInViewController alloc] init];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if([identification isEqualToString:@"YCJXCTJ"] && indexPath.row == 1){
        //原材消耗统计表报表
        MCConsumeViewController *viewController = [[MCConsumeViewController alloc] init];
        [self.navigationController pushViewController:viewController animated:YES];
        
    }
}


#pragma mark
#pragma mark - IBAction

- (void)realTimeSelector:(GEObjectButton*)sender
{
    NSArray *objectArray = sender.object;
    NSMutableArray *mutilNames = [NSMutableArray array];
    NSMutableArray *mutilTitles = [NSMutableArray array];
    NSMutableArray *mutilValues = [NSMutableArray array];
    NSMutableArray *mutilWidths = [NSMutableArray array];
    
    for(int i=1; i<objectArray.count; i++){
        NSArray *itemChart = [objectArray objectAtIndex:i];
        NSArray *titles = @[@"仓储位置",@"最大数量",@"剩余数量"];
        NSMutableArray *valueArray = [NSMutableArray array];
        
        for(NSDictionary *dic in itemChart){
            NSString *ccwz = [dic objectFormatStringForKey:@"仓储位置" defaults:@"-"];
            NSString *zdsl = [dic objectFormatStringForKey:@"最大数量" defaults:@"-"];
            NSString *sysl = [dic objectFormatStringForKey:@"剩余数量" defaults:@"-"];
            [valueArray addObject:@[ccwz,zdsl,sysl]];
        }
        
        CGFloat itemWidth = SuperWidth/12;
        NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*3)];
        NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*4)];
        NSNumber *value3 = [NSNumber numberWithFloat:(itemWidth*4)];
        NSArray *widths = @[value1,value2,value3];
        
        [mutilTitles addObject:titles];
        [mutilValues addObject:valueArray];
        [mutilWidths addObject:widths];
    }
    
    NSArray *nowArray = [objectArray firstObject];
    for (NSDictionary *dicValue in nowArray) {
        NSString *ckmc = [dicValue objectFormatStringForKey:@"生产线" defaults:@"未知"];
        ckmc = [NSString stringWithFormat:@"原材实时库存容量(吨)(%@)",ckmc];
        [mutilNames addObject:ckmc];
    }
    
    GEShowMutliPopupReportView *view = [GEShowMutliPopupReportView shareInitialize];
    [view showName:mutilNames titles:mutilTitles data:mutilValues widths:mutilWidths];
}

- (void)changeSelector:(GEObjectButton*)sender
{
    NSArray *objectArray = sender.object;
    NSArray *titles = @[@"材料名称",@"实际重量",@"运单重量"];
    NSMutableArray *valueArray = [NSMutableArray array];
    
    for(NSDictionary *dic in objectArray){
        NSString *ckwz = [dic objectFormatStringForKey:@"材料名称" defaults:@"-"];
        NSString *pm = [dic objectFormatFloatStringForKey:@"净重" retain:1 format:@"%@"];;
        NSString *gg = [dic objectFormatFloatStringForKey:@"供方重量" retain:2 format:@"%@"];;
        [valueArray addObject:@[ckwz,pm,gg]];
    }
    
    CGFloat itemWidth = SuperWidth/11;
    NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*4)];
    NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*3)];
    NSNumber *value3 = [NSNumber numberWithFloat:(itemWidth*3)];
    NSArray *widths = @[value1,value2,value3];
    
    GEShowMutliPopupReportView *view = [GEShowMutliPopupReportView shareInitialize];
    [view showName:@[@"近3天原材进料统计明细(吨、元)"] titles:@[titles] data:@[valueArray] widths:@[widths]];
}

@end
